import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:online_bookstore/constants/app_constants.dart';
import 'package:online_bookstore/models/book.dart';
import 'package:online_bookstore/providers/book_provider.dart';
import 'package:online_bookstore/providers/cart_provider.dart';
import 'package:online_bookstore/widgets/book_card.dart';
import 'package:online_bookstore/widgets/category_chips.dart';
import 'package:online_bookstore/widgets/loading_shimmer.dart';
import 'package:online_bookstore/widgets/error_widget.dart';
import 'package:online_bookstore/screens/books/book_detail_screen.dart';

class BooksListScreen extends ConsumerStatefulWidget {
  const BooksListScreen({super.key});

  @override
  ConsumerState<BooksListScreen> createState() => _BooksListScreenState();
}

class _BooksListScreenState extends ConsumerState<BooksListScreen> {
  final ScrollController _scrollController = ScrollController();
  String? _selectedCategory;
  String? _searchQuery;
  String _sortBy = 'title';
  String _sortOrder = 'asc';

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadBooks();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent * 0.8) {
      _loadMoreBooks();
    }
  }

  void _loadBooks() {
    ref.read(booksProvider.notifier).refreshBooks(
      category: _selectedCategory,
      search: _searchQuery,
      sortBy: _sortBy,
      sortOrder: _sortOrder,
    );
  }

  void _loadMoreBooks() {
    ref.read(booksProvider.notifier).loadBooks(
      category: _selectedCategory,
      search: _searchQuery,
      sortBy: _sortBy,
      sortOrder: _sortOrder,
    );
  }

  void _onCategorySelected(String? category) {
    setState(() {
      _selectedCategory = category;
    });
    _loadBooks();
  }

  void _onSearch(String query) {
    setState(() {
      _searchQuery = query.isEmpty ? null : query;
    });
    _loadBooks();
  }

  void _onSortChanged(String sortBy, String sortOrder) {
    setState(() {
      _sortBy = sortBy;
      _sortOrder = sortOrder;
    });
    _loadBooks();
  }

  @override
  Widget build(BuildContext context) {
    final booksState = ref.watch(booksProvider);
    final cartItemsCount = ref.watch(cartItemsCountProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Online Bookstore'),
        actions: [
          Stack(
            children: [
              IconButton(
                icon: const Icon(Icons.shopping_cart),
                onPressed: () {
                  // Navigate to cart screen
                },
              ),
              if (cartItemsCount > 0)
                Positioned(
                  right: 8,
                  top: 8,
                  child: Container(
                    padding: const EdgeInsets.all(2),
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.error,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    constraints: const BoxConstraints(
                      minWidth: 16,
                      minHeight: 16,
                    ),
                    child: Text(
                      '$cartItemsCount',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
            ],
          ),
        ],
      ),
      body: Column(
        children: [
          // Search Bar
          Padding(
            padding: const EdgeInsets.all(AppConstants.defaultPadding),
            child: TextField(
              decoration: InputDecoration(
                hintText: 'Search books...',
                prefixIcon: const Icon(Icons.search),
                suffixIcon: _searchQuery != null
                    ? IconButton(
                        icon: const Icon(Icons.clear),
                        onPressed: () => _onSearch(''),
                      )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(AppConstants.borderRadius),
                ),
              ),
              onChanged: _onSearch,
            ),
          ),

          // Category Chips
          const CategoryChips(),

          // Sort Options
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: AppConstants.defaultPadding),
            child: Row(
              children: [
                const Text('Sort by:'),
                const SizedBox(width: 8),
                DropdownButton<String>(
                  value: _sortBy,
                  items: const [
                    DropdownMenuItem(value: 'title', child: Text('Title')),
                    DropdownMenuItem(value: 'price', child: Text('Price')),
                    DropdownMenuItem(value: 'rating', child: Text('Rating')),
                    DropdownMenuItem(value: 'published_date', child: Text('Date')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      _onSortChanged(value, _sortOrder);
                    }
                  },
                ),
                const SizedBox(width: 16),
                DropdownButton<String>(
                  value: _sortOrder,
                  items: const [
                    DropdownMenuItem(value: 'asc', child: Text('Ascending')),
                    DropdownMenuItem(value: 'desc', child: Text('Descending')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      _onSortChanged(_sortBy, value);
                    }
                  },
                ),
              ],
            ),
          ),

          const SizedBox(height: 16),

          // Books List
          Expanded(
            child: _buildBooksList(booksState),
          ),
        ],
      ),
    );
  }

  Widget _buildBooksList(BooksState state) {
    if (state.isLoading && state.books.isEmpty) {
      return const LoadingShimmer();
    }

    if (state.error != null && state.books.isEmpty) {
      return CustomErrorWidget(
        message: state.error!,
        onRetry: _loadBooks,
      );
    }

    if (state.books.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.book_outlined,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              'No books found',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async => _loadBooks(),
      child: MasonryGridView.count(
        controller: _scrollController,
        crossAxisCount: 2,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        padding: const EdgeInsets.all(AppConstants.defaultPadding),
        itemCount: state.books.length + (state.isLoading ? 2 : 0),
        itemBuilder: (context, index) {
          if (index >= state.books.length) {
            return const LoadingShimmer();
          }

          final book = state.books[index];
          return BookCard(
            book: book,
            onTap: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => BookDetailScreen(book: book),
                ),
              );
            },
          );
        },
      ),
    );
  }
}
